package net.flintx.array;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by flintx on 2018/1/14.
 */
public class DegreeOfAnArray {
    public int findShortestSubArray(int[] nums) {
        if (nums.length < 2)
            return nums.length;
        HashMap<Integer, Integer> count = new HashMap<>();
        HashMap<Integer, Integer> start = new HashMap<>();
        HashMap<Integer, Integer> end = new HashMap<>();
        int maxCount = 1;
        for (int i = 0; i < nums.length; i++) {
            if (count.containsKey(nums[i])) {
                int newCount = count.get(nums[i]) + 1;
                count.put(nums[i], newCount);
                maxCount = Math.max(maxCount, newCount);
            } else {
                count.put(nums[i], 1);
            }
            if (!start.containsKey(nums[i])) {
                start.put(nums[i], i);
            }
        }

        for (int i = nums.length - 1; i >= 0; i--) {
            if (!end.containsKey(nums[i])) {
                end.put(nums[i], i);
            }
        }

        int minLen = Integer.MAX_VALUE;
        for (Map.Entry<Integer, Integer> e : count.entrySet()) {
            if (e.getValue() == maxCount) {
                minLen = Math.min(minLen, end.get(e.getKey()) - start.get(e.getKey()) + 1);
            }
        }
        return minLen;
    }

    public static void main(String[] args) {
        int[] nums = {2, 1};
        System.out.println(new DegreeOfAnArray().findShortestSubArray(nums));
    }
}
